package main

import (
	"fmt"
	"net"
	"os"

	"gitee.com/ezios/file-assistant/client"
	"gitee.com/ezios/file-assistant/core"
	"gitee.com/ezios/file-assistant/core/config"
	"gitee.com/ezios/file-assistant/server"
)

func main() {
	args := os.Args
	mode := "server"
	if len(args) > 1 {
		mode = args[1]
	}
	fmt.Println("模式：",mode)


	config := config.Load()

	if mode == "server" {
		fmt.Println("接收端模式")
		runServer(&config)
	} else {
		fmt.Println("发送端模式")
		runClient(&config)
	}

}
func runClient(c *config.Config) {
	client := client.NewClient(c.Ip, c.Port)
	file := input()
	transferFile := core.LoadFile(file)
	client.Work(&transferFile)
}
func runServer(c *config.Config) {
	server := server.NewServer(c.Ip, c.Port)
	server.Connect()
	server.Accept()
}
func input() *os.File {
	var filePath string
	var file *os.File
	fmt.Println("请输入文件路径：")
	fmt.Scan(&filePath)
	fmt.Println()
	file, err := os.Open(filePath)
	if err != nil {
		fmt.Println("文件不存在")
	}

	return file
}

func main3() {
	listener, err := net.Listen("tcp", "127.0.0.1:8080")
	if err != nil {
		fmt.Println("监听失败", err.Error())
		return
	}

	defer listener.Close()

	conn, err := listener.Accept()
	if err != nil {
		fmt.Println("连接失败", err.Error())
		return
	}

	defer conn.Close()

	var read = make([]byte, 1024)
	num, err := conn.Read(read)
	if err != nil {
		fmt.Println("读取失败", err.Error())
		return
	}

	fmt.Println("准备下载文件：")
	fmt.Println(string(read[:num]))

	_, err = os.Create("./download/" + string(read[:num]))
	if err != nil {
		fmt.Println("创建文件失败", err.Error())
		return
	}
	downloadFile, _ := os.OpenFile("./download/"+string(read[:num]), os.O_APPEND, os.ModeAppend.Perm())
	defer downloadFile.Close()
	for {
		num, err = conn.Read(read)
		if err != nil {
			if err.Error() != "EOF" {
				fmt.Println("读取失败", err.Error())
				break
			}
			fmt.Println("下载完成")
			break
		}

		downloadFile.Write(read[:num])
	}
}

func readFile() {
	var filePath string
	fmt.Println("请输入文件路径：")
	fmt.Scan(&filePath)
	fmt.Println()
	file, err := os.Open(filePath)
	if err != nil {
		fmt.Println("文件不存在")
		return
	}
	// 关闭文件
	defer file.Close()
	// 读取文件
	data := make([]byte, 10)
	readNum, err := file.Read(data)
	if err != nil {
		fmt.Println("读取文件失败")
		return
	}
	fmt.Println(string(data[:readNum]))
}
